using System;

namespace Lt.Workflow
{
    public class SequentialWorkflow : BaseWorkflow, IWorkflow
    {
        public virtual void Add(IWorkflowItem item)
        {
            this.Items.Enqueue(item);
        }

        public virtual void Execute(object context, bool continueOnError, Action<IWorkflowItem, Exception> onError = null)
        {
            foreach (var workflowItem in Items)
            {
                try
                {
                    workflowItem.Run(context);
                }
                catch (Exception ex)
                {
                    if (onError != null)
                    {
                        onError(workflowItem, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }

        public void Cleanup()
        {
            this.Clear();
        }

        public string GetStatus()
        {
            return string.Empty;
        }
    }


    public class SequentialWorkflow<TContext> : SequentialWorkflow
    {
        public override void Execute(object context, bool continueOnError, Action<IWorkflowItem, Exception> onError = null)
        {
            if (!(context is TContext))
            {
                throw new ArgumentException(string.Format("Context is of incompatible type {0} instead of {1}", context.GetType().Name, typeof(TContext).Name));
            }
            base.Execute(context, continueOnError, onError);
        }
    }
}